<template>
  <div class="pic-wrap">
    <a-upload
      :customRequest="httpRequest"
      :file-list="fileList"
      :beforeUpload="beforeUpload"
      @change="uploadfile"
    >
      <div v-if="fileList.length < numlimit">
        <a-button :loading="loading" :disabled="loading">
          <a-icon type="upload" />
          上传
        </a-button>
      </div>
    </a-upload>
  </div>
</template>

<script>
import { uploadfile,querySignature,uploadOSSFile } from '@/api/index'
import { fillUrl } from '@/utils'
import uuidv1 from "uuid/v1"
import { decrypt,encrypt,ossType } from '@/api/aesUtil'

/**
 *属性
 *@fileList默认值
 * [{
          uid: '-1',
          name: 'image.png',
          status: 'done',
          url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png'
    }]
 *
 *@limit 文件限制的个数
 *方法
 * gainList 获取文件列表
 * gainStatus 获取的文件是否在上传中
 */

export default {
  name: 'upfilescomp',
  props: ['filelistarr', 'limit'],
  data() {
    return {
      loading: false,
      fileList: [],
      numlimit: 1,
      clent: null
    }
  },
  methods: {
    async httpRequest(info) {
      const { file } = info
      try {
        let that = this
        const signRes = await querySignature("other")
        
        if (signRes.code === 0) {
            if(signRes.data.tyCloudFlag=='0'){
              const filename = file.name;
              const size = file.size;
              console.log("signRes",signRes,filename)
              const fileExt = filename.split(".");
              const uuid = uuidv1();
              let formData = new FormData();
              //注意formData里append添加的键的大小写
              formData.append('key', signRes.data.dir + uuid + "." + fileExt[1]); //存储在oss的文件路径
              formData.append('OSSAccessKeyId', signRes.data.accessid); //accessKeyId
              formData.append('policy', signRes.data.policy); //policy
              formData.append('Signature', signRes.data.signature); //签名
              //formData.append('callback', signRes.callback); //回调
              formData.append('success_action_status', 200); //成功后返回的操作码
              //如果是base64文件，那么直接把base64字符串转成blob对象进行上传就可以了
              formData.append("file", file);

              var res = await uploadOSSFile(signRes.data.host, formData);
              const imageUrl = signRes.data.host.replaceAll('http://','https://')+'/'+signRes.data.dir + uuid + "." + fileExt[1];
            // const { name, uid, size } =
              const obj =  { 'name':filename, 'uid':uuid, 'size':size }
              obj.url = imageUrl
              console.log(obj);
              this.fileList.push(obj)
              console.log(this.filelistarr)
              this.$emit('gainList', this.fileList)
              this.loading = false
              this.$message.success('上传成功')
            }
            else
            {
              
              const filename = file.name;
              const size = file.size;

              const fileExt = filename.split(".");
              const uuid = uuidv1();
              
              var params = {
                Body: file,
                Bucket: signRes.data.bucket,
                Key: signRes.data.dir + uuid + "." + fileExt[1]
              }
              that.client.putObject(params, function (err, data) {
                if (err) {
                  that.loading = false
                  that.$message.error('上传失败')
                } else {
  
                  const imageUrl = signRes.data.host+'/'+signRes.data.dir + uuid + "." + fileExt[1];
                  const obj =  { 'name':filename, 'uid':uuid, 'size':size }
                  obj.url = imageUrl

                  that.fileList.push(obj)
                  console.log(this.filelistarr)
                  that.$emit('gainList', this.fileList)
                  that.loading = false
                  that.$message.success('上传成功')
                }
              })

            }
        }
      } catch (e) {
        console.info('error??', e)
        this.loading = false
        this.$message.error('上传失败')
      }
    },
    beforeUpload(file) {
      const isFile =
        file.type ===
          'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
        file.type === 'application/msword' ||
        file.type === 'application/pdf' ||
        file.type === 'text/plain' ||
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'text/x-setext' ||
        file.type === 'application/x-earthtime'
      if (!isFile) {
        this.loading = false
        this.$message.error(
          '请上传txt/doc/xls/docx/xlsx/jpg/jpeg/png/pdf/et格式的文件!'
        )
      }
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('文件大小不能超过5M!')
      }
      // console.log(isFile, isLt2M)
      return isFile && isLt2M
    },
    uploadfile(info) {
      this.loading = true
      if (info.file.status === 'removed') {
        this.loading = false
        this.fileList = info.fileList
        this.$emit('update:filelistarr', this.fileList)
        this.$emit('gainList', this.fileList)
      }
      if (info.file.status === 'done') {
        // console.log(1111)
      }
      if (!info.file.status) {
        this.loading = false
      }
    },
    initOss () {
      let that = this
      querySignature("init").then(res=>{
        if (res.code === 0 && res.data.tyCloudFlag=='1') {
          that.client = new ObsClient({
              access_key_id: res.data.accessid,       
              secret_access_key: decrypt(res.data.signature),   
              server : res.data.endPoint
          });
        }
      })
    }
  },
  created() {
    if (this.filelistarr instanceof Array) {
      this.fileList = this.filelistarr
    }
    if (this.limit !== undefined) {
      this.numlimit = this.limit
    }
  },
  mounted() {
      this.initOss()
  },
  watch: {
    filelistarr: {
      handler(val) {
        this.fileList = val
        this.$forceUpdate()
      },
      deep: true
    },
    loading(newValue) {
      this.$emit('gainStatus', newValue)
    }
  }
}
</script>

<style lang="less" scoped>
.pic-wrap {
  .change-img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -5px;
    margin-left: -8px;
  }
  /deep/ .ant-upload {
    padding: 0;
  }
  img {
    width: 100px;
    height: auto;
  }
  .up-bc {
    opacity: 0.5;
  }
}
</style>
